package javawork;

import java.util.Scanner;

public class section9_12 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // 提示用户输入四个端点坐标
        System.out.print("Enter x1, y1, x2, y2, x3, y3, x4, y4: ");
        double x1 = input.nextDouble();
        double y1 = input.nextDouble();
        double x2 = input.nextDouble();
        double y2 = input.nextDouble();
        double x3 = input.nextDouble();
        double y3 = input.nextDouble();
        double x4 = input.nextDouble();
        double y4 = input.nextDouble();

        // 根据线段端点计算线性方程系数（ax + by = e 和 cx + dy = f）
        // 线段1：(y2 - y1)x - (x2 - x1)y = (y2 - y1)x1 - (x2 - x1)y1
        double a = y2 - y1;
        double b = x1 - x2;  // 等价于 -(x2 - x1)
        double e = a * x1 + b * y1;

        // 线段2：(y4 - y3)x - (x4 - x3)y = (y4 - y3)x3 - (x4 - x3)y3
        double c = y4 - y3;
        double d = x3 - x4;  // 等价于 -(x4 - x3)
        double f = c * x3 + d * y3;

        // 创建LinearEquation对象求解方程组
        LinearEquation equation = new LinearEquation(a, b, c, d, e, f);

        // 判断是否有交点并输出结果
        if (equation.isSolvable()) {
            double x = equation.getX();
            double y = equation.getY();
            System.out.println("The intersecting point is at (" + x + ", " + y + ")");
        } else {
            System.out.println("The two lines do not intersect");
        }

        input.close();
    }
}

// 复用之前实现的LinearEquation类
class LinearEquation {
    private double a, b, c, d, e, f;

    public LinearEquation(double a, double b, double c, double d, double e, double f) {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
        this.e = e;
        this.f = f;
    }

    public double getA() { return a; }
    public double getB() { return b; }
    public double getC() { return c; }
    public double getD() { return d; }
    public double getE() { return e; }
    public double getF() { return f; }

    public boolean isSolvable() {
        return (a * d - b * c) != 0;
    }

    public double getX() {
        double denominator = a * d - b * c;
        return (e * d - b * f) / denominator;
    }

    public double getY() {
        double denominator = a * d - b * c;
        return (a * f - e * c) / denominator;
    }
}
